# # import cv2
# # import insightface
# # import numpy as np
# # from ultralytics import YOLO
# #
# # # 加载YOLOv8模型（新版ultralytics库）
# # model = YOLO('yolov5s.pt')  # 或者换成yolov8n.pt等
# #
# # # 加载InsightFace
# # face_model = insightface.app.FaceAnalysis(name='buffalo_l')
# # face_model.prepare(ctx_id=0)
# #
# # my_embedding = np.load("my_face.npy")
# #
# #
# # def is_me(face_embedding, threshold=0.5):
# #     dist = np.linalg.norm(face_embedding - my_embedding)
# #     return dist < threshold
# #
# #
# # cap = cv2.VideoCapture(0)
# # if not cap.isOpened():
# #     print("❌ 摄像头打开失败")
# #     exit()
# #
# # print("✅ 开始检测，按 Q 退出")
# #
# # while True:
# #     ret, frame = cap.read()
# #     if not ret:
# #         break
# #
# #     results = model(frame)[0]  # ultralytics新版API
# #
# #     stranger_detected = False
# #
# #     for result in results.boxes.data.cpu().numpy():
# #         x1, y1, x2, y2, conf, cls = result
# #         if int(cls) != 0:  # 只检测person类
# #             continue
# #
# #         face_img = frame[int(y1):int(y2), int(x1):int(x2)]
# #         if face_img.size == 0:
# #             continue
# #
# #         faces = face_model.get(face_img)
# #         if not faces:
# #             continue
# #         face_embedding = faces[0].embedding
# #
# #         if is_me(face_embedding):
# #             label = "我"
# #             color = (0, 255, 0)
# #         else:
# #             label = "陌生人"
# #             color = (0, 0, 255)
# #             stranger_detected = True
# #
# #         cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), color, 2)
# #         cv2.putText(frame, label, (int(x1), int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2)
# #
# #     if stranger_detected:
# #         print("🚨 陌生人出现，伪装窗口！")
# #         try:
# #             print('老板出没！！！')
# #         except:
# #             print('出现异常')
# #
# #     cv2.imshow("Monitoring", frame)
# #     if cv2.waitKey(1) & 0xFF == ord('q'):
# #         break
# #
# # cap.release()
# # cv2.destroyAllWindows()
# import cv2
# import insightface
# import numpy as np
# from ultralytics import YOLO
#
# model = YOLO('yolov8n.pt')  # 轻量模型
#
# face_model = insightface.app.FaceAnalysis(name='buffalo_l')
# face_model.prepare(ctx_id=-1)  # CPU模式，-1表示CPU
#
# my_embedding = np.load("my_face.npy")
#
# def is_me(face_embedding, threshold=0.7):
#     dist = np.linalg.norm(face_embedding - my_embedding)
#     return dist < threshold
#
# cap = cv2.VideoCapture(0)
# cap.set(cv2.CAP_PROP_FRAME_WIDTH, 240)
# cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 120)
#
# frame_count = 0
# detect_interval = 3
# boxes = []
#
# while True:
#     ret, frame = cap.read()
#     if not ret:
#         break
#     frame_count += 1
#
#     if frame_count % detect_interval == 0:
#         results = model(frame)[0]
#         boxes = results.boxes.data.cpu().numpy()
#
#     stranger_detected = False
#
#     for result in boxes:
#         x1, y1, x2, y2, conf, cls = result
#         if int(cls) != 0:
#             continue
#
#         face_img = frame[int(y1):int(y2), int(x1):int(x2)]
#         if face_img.size == 0:
#             continue
#
#         faces = face_model.get(face_img)
#         if not faces:
#             continue
#
#         face_embedding = faces[0].embedding
#
#         if is_me(face_embedding):
#             label = "我"
#             color = (0, 255, 0)
#         else:
#             label = "陌生人"
#             color = (0, 0, 255)
#             stranger_detected = True
#
#         cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), color, 2)
#         cv2.putText(frame, label, (int(x1), int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2)
#
#     if stranger_detected:
#         print("🚨 陌生人出现，伪装窗口！")
#
#     cv2.imshow("Monitoring", frame)
#     if cv2.waitKey(1) & 0xFF == ord('q'):
#         break
#
# cap.release()
# cv2.destroyAllWindows()
import cv2
import insightface
import numpy as np
from ultralytics import YOLO

model = YOLO('yolov8n.pt')

face_model = insightface.app.FaceAnalysis(name='buffalo_l')
face_model.prepare(ctx_id=-1)  # CPU模式

my_embedding = np.load("my_face.npy")

def is_me(face_embedding, threshold=15):
    dist = np.linalg.norm(face_embedding - my_embedding)
    print(f"距离: {dist:.3f}")
    return dist < threshold

cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 120)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 60)

frame_count = 0
detect_interval = 3
boxes = []

while True:
    ret, frame = cap.read()
    if not ret:
        break
    frame_count += 1
    if frame_count % detect_interval == 0:
        results = model(frame)[0]
        boxes = results.boxes.data.cpu().numpy()
    stranger_detected = False
    h, w, _ = frame.shape
    for result in boxes:
        x1, y1, x2, y2, conf, cls = result
        if int(cls) != 0:
            continue

        x1, y1 = max(0, int(x1)), max(0, int(y1))
        x2, y2 = min(w - 1, int(x2)), min(h - 1, int(y2))
        face_img = frame[y1:y2, x1:x2]
        if face_img.size == 0:
            continue

        faces = face_model.get(face_img)
        if not faces:
            continue

        face_embedding = faces[0].embedding

        if is_me(face_embedding):
            label = "我"
            color = (0, 255, 0)
        else:
            label = "陌生人"
            color = (0, 0, 255)
            stranger_detected = True

        cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
        cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2)

    if stranger_detected:
        print("🚨 陌生人出现，伪装窗口！")

    cv2.imshow("Monitoring", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
